<?php

namespace App\Http\Controllers\User;

use App\Http\Classes\Common;
use App\Http\Classes\Email;
use App\Http\Classes\User;
use App\Http\Classes\PhoneAli;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    /*
     * COOKIE自动登录
     * GET
     * $_COOKIE['USER_ID']  $_COOKIE['USER_TOKEN']
     */
    public function autoLogin(Request $request)
    {
        try
        {
            if ( isset($_COOKIE['USER_ID']) && isset($_COOKIE['USER_TOKEN']) )
            {
                $user = new User($_COOKIE['USER_ID']);
                $data = $user->loginByCookie($_COOKIE['USER_TOKEN']);
                if ( $data )
                {
                    return $this->response(1, '登录成功', $data);
                }
                else
                {
                    setcookie('USER_ID', '', time() - 3600, '/' );
                    setcookie('USER_TOKEN', '', time() - 3600, '/' );
                    return $this->response(0, '令牌过期，请重新登录', [], $user->getMessage());
                }
            }
            else
            {
                return $this->response(0, '令牌过期，请重新登录', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }
    /*
     * 用户登录
     * POST
     * user  password
     */
    public function login(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['user']) && isset($data['password']) && !empty($data['user']) && !empty($data['password']))
            {
                if ( Common::isEmail($data['user']) )
                {
                    return $this->loginByEmail($data['user'], $data['password']);
                }
                else
                {
                    return $this->loginByPhone($data['user'], $data['password']);
                }
            }
            else
            {
                return $this->response(0,'用户名或密码不能为空');
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 电话号码登录
     *
     */
    private function loginByPhone($phone, $password)
    {
        try
        {
            $user = new User();
            $userinfo = $user->loginByPhone($phone, $password);
            if ( $userinfo )
            {
                setcookie('USER_ID', $userinfo->id, time() + DAY7, '/' );
                setcookie('USER_TOKEN', $userinfo->token, time() + DAY7, '/' );
                return $this->response(1, '登录成功！',$userinfo);
            }
            else
            {
                setcookie('USER_ID', '', time() - 3600, '/' );
                setcookie('USER_TOKEN', '', time() - 3600, '/' );
                return $this->response(0, '登录失败！' . $user->getMessage(),[]);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 邮箱登录
     */
    private function loginByEmail($email, $password)
    {
        try
        {
            $user = new User();
            $userinfo = $user->loginByEmail($email, $password);
            if ( $userinfo )
            {
                setcookie('USER_ID', $userinfo->id, time() + DAY7, '/' );
                setcookie('USER_TOKEN', $userinfo->token, time() + DAY7, '/' );
                return $this->response(1, '登录成功！',$userinfo);
            }
            else
            {
                setcookie('USER_ID', '', time() - 3600, '/' );
                setcookie('USER_TOKEN', '', time() - 3600, '/' );
                return $this->response(0, '登录失败！' . $user->getMessage(),[]);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 用户登出
     * GET
     *
     */
    public function logOut(Request $request)
    {
        try
        {
            setcookie('USER_ID', '', time() - 3600, '/' );
            setcookie('USER_TOKEN', '', time() - 3600, '/' );
            return $this->response(1, '登出成功', []);
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 电话号码注册
     * POST
     * phone   password   code
     */
    public function registerByPhone(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['phone']) && isset($data['password']) && isset($data['code']) )
            {
                if ( ! Common::isPassword($data['password']) )
                {
                    return $this->response(0, '密码不规范', $data['password']);
                }
                $phone = new PhoneAli( $data['phone'] );
                $phone = $phone->validatorRegisterCode( $data['code'] );
                if ( $phone )
                {
                    $dataArray = array();
                    $dataArray['phone'] = $data['phone'];
                    $dataArray['password'] = $data['password'];
                    $user = new User();
                    if ( $user->registerByPhone($dataArray) )
                    {
                        return $this->response(1, '注册成功', []);
                    }
                    else
                    {
                        return $this->response(0, '注册失败', []);
                    }
                }
                else{
                    //
                    return $this->response(0, '手机验证码错误', []);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 邮箱注册
     */
    public function registerByEmail(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset( $data['email'] ) && isset( $data['password'] ) )
            {
                if ( ! Common::isPassword($data['password']) )
                {
                    return $this->response(0, '密码不规范', $data['password']);
                }
                if ( Common::isEmail($data['email']) )
                {
                    if ( ! Common::isEmailExists($data['email']) )
                    {
                        $user = new User();
                        if ( $user->registerByEmail($data) )
                        {
                            return $this->response(1, '注册成功', []);
                        }
                        else
                        {
                            return $this->response(0, '注册失败', []);
                        }
                    }
                    else
                    {
                        return $this->response(0, '此邮箱已注册', $data['email']);
                    }
                }
                else
                {
                    return $this->response(0, '非法邮箱格式', $data['email']);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 获取注册手机验证码
     * POST
     * phone 
     */
    public function getRegisterPhoneCode(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['phone']) && Common::isPhone($data['phone']) )
            {
                if ( ! Common::isPhoneExists($data['phone']) )
                {
                    $phone = new PhoneAli($data['phone'], true);
                    if ( $phone->sendRegisterCode() )
                    {
                        return $this->response(1, '短信发送成功！', []);
                    }
                    else
                    {
                        return $this->response(0, '短信发送失败！', [], $phone->getMessage());
                    }
                }
                else
                {
                    return $this->response(0, '该手机号已注册', $data['phone']);
                }
            }
            else
            {
                return $this->response(0, '手机号码不正确', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 获取邮箱验证码
     */
    public function getEmailCode(Request $request)
    {
        try
        {
            $data = $request->all();
            $user = new User();
            if ( isset( $data['email'] ) &&
                Common::isEmail( $data['email'] && ! $user->isEmailExists( $data['email'] ) )
            )
            {
                $email = new Email( $data['email'] );
                if ( $email->sendRegisterEmail() )
                {
                    return $this->response(1, '邮件发送成功，请注意查收！', []);
                }
                else
                {
                    return $this->response(0, '邮件发送失败！', [], $email->getMessage());
                }
            }
            else
            {
                return $this->response(0, '参数错误！', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 获取修改密码的短信验证码
     * POST
     * phone
     */
    public function getResetPhoneCode(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['phone']) && Common::isPhone($data['phone']) )
            {
                if ( Common::isPhoneExists($data['phone']) )
                {
                    $phone = new PhoneAli($data['phone'], true);
                    if ( $phone->sendResetCode() )
                    {
                        return $this->response(1, '短信发送成功！', []);
                    }
                    else
                    {
                        return $this->response(0, '短信发送失败！', [], $phone->getMessage());
                    }
                }
                else
                {
                    return $this->response(0, '该手机号未注册！', $data['phone']);
                }
            }
            else
            {
                return $this->response(0, '手机号码不正确！', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 通过手机验证修改密码
     * POST
     * phone password code
     */
    public function updatePasswordByPhone(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['phone']) && isset($data['password']) && isset($data['code']) )
            {
                if ( ! Common::isPassword($data['password']) )
                {
                    return $this->response(0, '密码不规范', $data['password']);
                }
                if ( Common::isPhone($data['phone']) )
                {
                    $phone = new PhoneAli($data['phone']);
                    $phone = $phone->validatorResetCode($data['code']);
                    if ( $phone )
                    {
                        $user = new User();
                        if ( $user->updatePasswordByPhone($data['phone'], $data['password']) )
                        {
                            return $this->response(1, '密码修改成功', []);
                        }
                        else
                        {
                            return $this->response(0, '密码修改失败', [], $user->getMessage());
                        }
                    }
                    else
                    {
                        return $this->response(0, '手机验证码错误', []);
                    }
                }
                else
                {
                    return $this->response(0, '手机号码不正确！', []);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', []);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 发送修改密码链接到邮箱
     * POST
     * email  captcha
     */
    public function getResetEmail(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['captcha']) && captcha_check($data['captcha']) )
            {
                if ( isset($data['email']) && Common::isEmail($data['email']) && Common::isEmailExists($data['email']) )
                {
                    $email = new Email( $data['email'] );
                    if ( $email->sendResetEmail() )
                    {
                        return $this->response(1, '邮件发送成功，请注意查收！', []);
                    }
                    else
                    {
                        return $this->response(0, '邮件发送失败！', [], $email->getMessage());
                    }
                }
                else
                {
                    return $this->response(0,'该邮箱未注册', array('email' => $data['email']));
                }
            }
            else
            {
                return $this->response(0,'验证码错误',[]);
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 点击发送到邮件的链接
     * GET
     * _token
     */
    public function passwordReset(Request $request)
    {
        try 
        {
            $data = $request->all();
            if ( isset($data['_token']) )
            {
                $info = Redis::get( 'r_t_' . $data['_token'] );
                $info = json_decode($info);
                if ( $info )
                {
                    //dd($info);
                    return view('front.emailResetPassword')->with('info', $info);
                    //return $this->response(1, '', $info);
                }
                else
                {
                    return view('errors.403');
                }
            }
            else
            {
                return view('errors.403');
            }
        } 
        catch (\Exception $exception) 
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * 通过验证邮箱修改密码
     * POST
     * _token password
     */
    public function updatePasswordByEmail(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['token']) && isset($data['password']) )
            {
                if ( Common::isPassword($data['password']) )
                {
                    $info = Redis::get( 'r_t_' . $data['token'] );
                    $info = json_decode($info);
                    if ( $info )
                    {
                        //dd($info->id);
                        $user = new User( $info->id );
                        if ( $user->updatePassword( $data['password'] ) )
                        {
                            Redis::del('r_t_' . $data['token']);
                            return $this->response(1, '密码修改成功', []);
                        }
                        else
                        {
                            return $this->response(0, '密码修改失败', [], $user->getMessage());
                        }
                    }
                    else
                    {
                        return $this->response(0, '链接已失效', []);
                    }
                }
                else
                {
                    return $this->response(0, '密码不规范', $data['password']);
                }
            }
            else
            {
                return $this->response(0, '缺少参数', []);
            }
        }
        catch( \Exception $exception )
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * POST
     */
    public function weiboCreate(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['weibo']) && isset($data['email']) && isset($data['name']) && isset($data['password']) )
            {
                $dataArray['weibo'] = $data['weibo'];
                if (! Common::isEmail($data['email']))
                {
                    return $this->response(0, '邮箱格式不正确');
                }

                $dataArray['email'] = $data['email'];
                $dataArray['name'] = $data['name'];
                $dataArray['password'] = $data['password'];

                $user = new User();

                if ( $user->registerByWeibo($dataArray) )
                {
                    return $this->response(1, '注册成功', []);
                }
                else
                {
                    return $this->response(0, '注册失败', [], $user->getMessage());
                }
            }
            else
            {
                return $this->response(0, '缺少参数');
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    /*
     * POST
     */
    public function weiboBind(Request $request)
    {
        try
        {
            $data = $request->all();
            if ( isset($data['email']) && isset($data['password']) && isset($data['weibo']) )
            {
                if ( ! Common::isEmail($data['email']) )
                {
                    return $this->response(0, '邮箱格式不正确');
                }

                if ( ! Common::isEmailExists($data['email']) )
                {
                    return $this->response(0, '该邮箱未注册');
                }

                $dataArray = [];
                $dataArray['email'] = $data['email'];
                $dataArray['password'] = $data['password'];
                $dataArray['weibo'] = $data['weibo'];

                $user = new User();
                $userinfo = $user->bindWeibo($dataArray);
                if ( $userinfo )
                {
                    setcookie('USER_ID', $userinfo->id, time() + DAY7, '/' );
                    setcookie('USER_TOKEN', $userinfo->token, time() + DAY7, '/' );
                    setcookie('userInfo', json_encode($userinfo), time() + DAY7, '/' );
                    return $this->response(1, '绑定微博成功', $userinfo);
                }
                else
                {
                    return $this->response(0, '绑定微博失败！' . $user->getMessage(), []);
                }
            }
            else
            {
                return $this->response(0, '缺少参数');
            }
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }
}